package edu.gduf.controller;

import edu.gduf.domain.ResultInfo;
import edu.gduf.service.impl.InspectReportGenerateServiceImpl;
import edu.gduf.service.impl.SignInFormGenerateServiceImpl;
import edu.gduf.service.impl.political.PoliticalElectronicGenerateServiceImpl;
import edu.gduf.service.impl.political.PoliticalSituationGenerateServiceImpl;
import edu.gduf.service.impl.publicity.*;
import edu.gduf.service.impl.record.ActivistRecordGenerateServiceImpl;
import edu.gduf.service.impl.record.DeveloperRecordGenerateServiceImpl;
import edu.gduf.service.impl.record.PartyMemberRecordGenerateServiceImpl;
import org.apache.ibatis.io.Resources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * Demo Class
 *
 * @author 古市
 * @date 2020-08-25 14:17
 **/
@Controller
@RequestMapping("/file")
@ResponseBody
public class FileGenerateController {

    private SignInFormGenerateServiceImpl signInFormGenerateService;

    private InspectReportGenerateServiceImpl inspectReportGenerateService;

    private ActivistRecordGenerateServiceImpl activistRecordGenerateService;

    private DeveloperRecordGenerateServiceImpl developerRecordGenerateService;

    private PartyMemberRecordGenerateServiceImpl partyMemberRecordGenerateService;

    private PoliticalElectronicGenerateServiceImpl politicalElectronicGenerateService;

    private PoliticalSituationGenerateServiceImpl politicalSituationGenerateService;

    private FirstPublicityGenerateServiceImpl firstPublicityGenerateService;

    private SecondPublicityGenerateServiceImpl secondPublicityGenerateService;

    private ThirdPublicityGenerateServiceImpl thirdPublicityGenerateService;

    private FourthPublicityGenerateServiceImpl fourthPublicityGenerateService;

    private FifthPublicityGenerateServiceImpl fifthPublicityGenerateService;

    @Autowired
    public void setSignInFormGenerateService(SignInFormGenerateServiceImpl signInFormGenerateService) {
        this.signInFormGenerateService = signInFormGenerateService;
    }

    @Autowired
    public void setInspectReportGenerateService(InspectReportGenerateServiceImpl inspectReportGenerateService) {
        this.inspectReportGenerateService = inspectReportGenerateService;
    }

    @Autowired
    public void setActivistRecordGenerateService(ActivistRecordGenerateServiceImpl activistRecordGenerateService) {
        this.activistRecordGenerateService = activistRecordGenerateService;
    }

    @Autowired
    public void setDeveloperRecordGenerateService(DeveloperRecordGenerateServiceImpl developerRecordGenerateService) {
        this.developerRecordGenerateService = developerRecordGenerateService;
    }

    @Autowired
    public void setPartyMemberRecordGenerateService(PartyMemberRecordGenerateServiceImpl partyMemberRecordGenerateService) {
        this.partyMemberRecordGenerateService = partyMemberRecordGenerateService;
    }

    @Autowired
    public void setPoliticalElectronicGenerateService(PoliticalElectronicGenerateServiceImpl politicalElectronicGenerateService) {
        this.politicalElectronicGenerateService = politicalElectronicGenerateService;
    }

    @Autowired
    public void setPoliticalSituationGenerateService(PoliticalSituationGenerateServiceImpl politicalSituationGenerateService) {
        this.politicalSituationGenerateService = politicalSituationGenerateService;
    }

    @Autowired
    public void setFirstPublicityGenerateService(FirstPublicityGenerateServiceImpl firstPublicityGenerateService) {
        this.firstPublicityGenerateService = firstPublicityGenerateService;
    }

    @Autowired
    public void setSecondPublicityGenerateService(SecondPublicityGenerateServiceImpl secondPublicityGenerateService) {
        this.secondPublicityGenerateService = secondPublicityGenerateService;
    }

    @Autowired
    public void setThirdPublicityGenerateService(ThirdPublicityGenerateServiceImpl thirdPublicityGenerateService) {
        this.thirdPublicityGenerateService = thirdPublicityGenerateService;
    }

    @Autowired
    public void setFourthPublicityGenerateService(FourthPublicityGenerateServiceImpl fourthPublicityGenerateService) {
        this.fourthPublicityGenerateService = fourthPublicityGenerateService;
    }

    @Autowired
    public void setFifthPublicityGenerateService(FifthPublicityGenerateServiceImpl fifthPublicityGenerateService) {
        this.fifthPublicityGenerateService = fifthPublicityGenerateService;
    }

    private List<String> getNums(HttpServletRequest request){
        String nums = request.getParameter("student_nums");
        String[] split = nums.split(",");
        return Arrays.asList(split);
    }


    /**
     * 对返回数据进行预处理，
     * 处理输出文件路径
     * @param info 原始数据
     * @return 处理成功的数据
     */
    private ResultInfo dataPretreatment(ResultInfo info, String type){
        //如果响应的状态码是fail（即为0），则直接返回
        if (info.getStatus() == 0){
            return info;
        }
        String filepath = (String) info.getData();

        Map<String, String> result = new HashMap<>();
        //对文件路径进行切割
        String[] split = filepath.split("output/");
        result.put("filepath", (split[split.length-1]));

        result.put("filetype", type);
        info.setData(result);
        return info;
    }


    @RequestMapping("signin")
    public ResultInfo signinForm(HttpServletRequest request){
        List<String> nums = getNums(request);
        System.out.println(nums);
        //对数据进行预处理,并返回
        return dataPretreatment(signInFormGenerateService.fileGenerate(nums), "signin");
    }

    @RequestMapping("inspectorReport")
    public ResultInfo inspectorReport(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(inspectReportGenerateService.fileGenerate(nums), "inspectorReport");
    }

    @RequestMapping("politicalSituation")
    public ResultInfo politicalSituation(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(politicalSituationGenerateService.fileGenerate(nums), "politicalSituatio");
    }

    @RequestMapping("politicalElectronic")
    public ResultInfo politicalElectronic(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(politicalElectronicGenerateService.fileGenerate(nums), "政审电子表");
    }

    @RequestMapping("activistRecord")
    public ResultInfo activistRecord(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(activistRecordGenerateService.fileGenerate(nums), "activistRecord");
    }

    @RequestMapping("developerRecord")
    public ResultInfo developerRecord(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(developerRecordGenerateService.fileGenerate(nums), "developerRecord");
    }

    @RequestMapping("partyMemberRecord")
    public ResultInfo partyMemberRecord(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(partyMemberRecordGenerateService.fileGenerate(nums), "partyMemberRecord");
    }

    @RequestMapping("firstPublicity")
    public ResultInfo firstPublicity(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(firstPublicityGenerateService.fileGenerate(nums), "firstPublicity");
    }

    @RequestMapping("secondPublicity")
    public ResultInfo secondPublicity(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(secondPublicityGenerateService.fileGenerate(nums), "secondPublicity");
    }


    @RequestMapping("thirdPublicity")
    public ResultInfo thirdPublicity(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(thirdPublicityGenerateService.fileGenerate(nums), "thirdPublicity");
    }

    @RequestMapping("fourthPublicity")
    public ResultInfo fourthPublicity(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(fourthPublicityGenerateService.fileGenerate(nums), "fourthPublicity");
    }

    @RequestMapping("fifthPublicity")
    public ResultInfo fifthPublicity(HttpServletRequest request){
        List<String> nums = getNums(request);
        //对数据进行预处理,并返回
        return dataPretreatment(fifthPublicityGenerateService.fileGenerate(nums), "fifthPublicity");
    }


    @RequestMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response){

        String filepath = "output/" + request.getParameter("filepath");
        String[] split = filepath.split("/");
        String filetype = request.getParameter("filetype");
        String filename = split[split.length-1];
        filename = filetype + "_" + filename.split("\\.")[0] + "." + filename.split("\\.")[1];
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream out;
        try {

            bis = new BufferedInputStream(Resources.getResourceAsStream(filepath));

            out = response.getOutputStream();
            int i = bis.read(buff);
            while (i != -1){
                out.write(buff, 0, buff.length);
                out.flush();
                i = bis.read(buff);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //文件传输结束后，删除原有文件
            File file = null;
            try {
                file = Resources.getResourceAsFile(filepath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (file.exists()){
                System.out.println(file.getPath());
                boolean judge = file.delete();
                System.out.println(judge);
            }
        }

//        return ResultInfo.successInfo("成功下载");
    }

}
